package com.atguigu.controller;

import com.atguigu.entity.File;
import com.atguigu.service.FileService;
import com.atguigu.utils.Result;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    @Autowired
    FileService fileService;


    @GetMapping("/delete")
    public Result delete(Integer id) throws FileNotFoundException {
        //获取文件信息
        File deleteFile = fileService.findById(id);
        // 根据文件信息中的文件名字和文件存储路径获取文件输入流
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static" + deleteFile.getPath();
        java.io.File file = new java.io.File(realPath, deleteFile.getNewFileName());
        if(file.exists())file.delete();//立即删除

        //删除数据库中记录
        int i = fileService.delete(id);

        Result result = new Result();
        result.setStatus(true);
        result.setMessage("删除成功");
        return result;
    }


    @GetMapping("/openOnline")
    public void openOnline(Integer id, HttpServletResponse response) throws IOException {
        //获取文件信息
        File downloadFile = fileService.findById(id);
//        // 更新下载次数
//        downloadFile.setDownloadCount(downloadFile.getDownloadCount()+1);
//        fileService.update(downloadFile);

        // 根据文件信息中的文件名字和文件存储路径获取文件输入流
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static" + downloadFile.getPath();

        // 获取文件输入流
        FileInputStream is = new FileInputStream(new java.io.File(realPath,downloadFile.getNewFileName()));
        // 附件下载
        response.setHeader("content-disposition","inline;fileName="+ URLEncoder.encode(downloadFile.getOldFileName(),"utf-8"));
        //获取响应输出流
        ServletOutputStream os = response.getOutputStream();
        // 文件拷贝
        IOUtils.copy(is,os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }


    @GetMapping("/download")
    public void download(Integer id, HttpServletResponse response) throws IOException {
        //获取文件信息
        File downloadFile = fileService.findById(id);
        // 更新下载次数
        downloadFile.setDownloadCount(downloadFile.getDownloadCount()+1);
        fileService.update(downloadFile);

        // 根据文件信息中的文件名字和文件存储路径获取文件输入流
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static" + downloadFile.getPath();

        // 获取文件输入流
        FileInputStream is = new FileInputStream(new java.io.File(realPath,downloadFile.getNewFileName()));
        // 附件下载
        response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(downloadFile.getOldFileName(),"utf-8"));
        //获取响应输出流
        ServletOutputStream os = response.getOutputStream();
        // 文件拷贝
        IOUtils.copy(is,os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);


    }

    @PostMapping("/upload")
    public Result uploadFile(MultipartFile fileUpload,Integer userId) throws IOException {
        System.out.println("userId="+userId);
        // 获取文件原始名称
        String originalFilename = fileUpload.getOriginalFilename();
        // 获取文件的后缀
        String extension = "."+FilenameUtils.getExtension(originalFilename);
        // 生成新文件名
        String newFileName=new SimpleDateFormat("yyyMMddHHmmss").format(new Date())+ UUID.randomUUID().toString().replace("-","")+extension;
        // 文件的大小
        long size = fileUpload.getSize();
        // 文件的类型
        String contentType = fileUpload.getContentType();

        // 生成目录
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/files";
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String fileDirPath = realPath+"/"+format;
        java.io.File fileDir = new java.io.File(fileDirPath);
        if (!fileDir.exists())
            fileDir.mkdirs();

        // 处理文件上传
        //fileUpload.transferTo(new java.io.File(fileDir,newFileName));
        fileUpload.transferTo(new java.io.File(fileDirPath,newFileName));
        // 将文件信息保存到数据库
        File newFile = new File();
        newFile.setOldFileName(originalFilename).setNewFileName(newFileName).setExtend(extension)
                .setType(contentType).setSize((int)size).setPath("/files/"+format).setUserId(userId);
        System.out.println(newFile);

        fileService.save(newFile);

        System.out.println(newFile);

        // 返回结果信息
        Result result = new Result();
        result.setStatus(true);
        result.setMessage("文件上传成功");
        result.getMap().put("file",newFile);
        return result;
    }


    @GetMapping("/showFiles")
    public Result showFiles(Integer userId, HttpServletRequest request){
        String token = request.getHeader("token");
        System.out.println("showFiles..."+token);
        System.out.println(userId);
        Result result = new Result();
        List<File> files = fileService.getFileByUserId(userId);
        result.setStatus(true);
        result.setMessage("查找成功");
        result.getMap().put("files",files);
        return result;
    }
}
